package com.exposit.zbs.dao.impl;

import com.exposit.zbs.dao.IUserDAO;
import com.exposit.zbs.dao.base.BaseDAO;
import com.exposit.zbs.entity.UserEntity;
import com.exposit.zbs.model.User;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author Andrey
 */
@Repository
@Transactional
public class UserDAO extends BaseDAO<UserEntity, Long> implements IUserDAO {

	//@Autowired
	//    private SessionFactory sessionFactory;
	@Override
	public UserEntity findByLogin(String login) {

		UserEntity result = (UserEntity) getSession().createCriteria(UserEntity.class).add(Restrictions.eq("userLogin", login)).uniqueResult();

		return result;

	}

	@Override
	public boolean checkExistingByLoginOrEmail(String login, String email) {

		Long users = (Long) sessionFactory.getCurrentSession().createCriteria(UserEntity.class).setProjection(Projections.rowCount()).add(Restrictions.disjunction().add(Restrictions.eq("userLogin", login)).add(Restrictions.eq("userEmail", email))).uniqueResult();
		return (users > 0);
	}

	@SuppressWarnings("unchecked")
	public List<User> listUser() {

		return sessionFactory.getCurrentSession().createQuery("from user").list();
	}

}
